package com.cmc.cloud.cmclink.doc.controller.admin;

import com.cmc.cloud.cmclink.bdt.api.base.FinanceItemApi;
import com.cmc.cloud.cmclink.doc.constants.UrlConstants;
import com.cmc.cloud.cmclink.doc.convert.FinanceItemConvert;
import com.cmc.cloud.cmclink.doc.convert.LocalCostRateConvert;
import com.cmc.cloud.cmclink.doc.entity.LocalCostRateDO;
import com.cmc.cloud.cmclink.doc.rpcservice.CustomerRpcService;import com.cmc.cloud.cmclink.doc.service.LocalCostRateService;
import com.cmc.cloud.cmclink.doc.vo.localcostratevo.*;
import com.cmes.framework.biz.advice.annotations.UseResponsePropertyAdvice;
import com.cmes.framework.common.pojo.CommonResult;
import com.cmes.framework.common.pojo.PageResult;
import com.cmes.framework.excel.core.util.ExcelUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 提单本地费用费率前端接口Controller
 *
 * @author codegen
 */
@Tag(name = "管理后台 - 进口提单本地费用费率")
@RestController
@Validated
@RequestMapping(UrlConstants.APPLICATION_URL +"/im-local-cost-rate")
public class ImLocalCostRateController {
    @Resource
    private LocalCostRateService localCostRateService;
    @Resource
    private FinanceItemApi financeItemApi;

    @Resource
    private CustomerRpcService nameTransferService;

    @Operation(summary = "创建进口提单本地费用费率")
    @PostMapping("/create")
    @PreAuthorize("@ss.hasPermission('doc:import-local-cost-rate:create')")
    public CommonResult<Long> createLocalCostRate(@Valid @RequestBody LocalCostRateCreateReqVO createReqVO) {
        localCostRateService.createLocalCostRate(createReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "更新进口提单本地费用费率")
    @PostMapping("/update")
    @PreAuthorize("@ss.hasPermission('doc:import-local-cost-rate:update')")
    public CommonResult<Void> updateLocalCostRate(@Valid @RequestBody LocalCostRateUpdateReqVO updateReqVO) {
        localCostRateService.updateLocalCostRate(updateReqVO);
        return CommonResult.success();
    }

    @Operation(summary = "删除进口提单本地费用费率")
    @PostMapping("/delete/{id}")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('doc:import-local-cost-rate:update')")
    public CommonResult<Void> deleteLocalCostRate(@PathVariable("id") Long id) {
        localCostRateService.deleteLocalCostRate(id);
        return CommonResult.success();
    }

    @Operation(summary = "获得进口提单本地费用费率")
    @GetMapping("/get/{id}")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<LocalCostRateRespVO> getLocalCostRate(@PathVariable("id") Long id) {
        LocalCostRateDO localCostRate = localCostRateService.getLocalCostRate(id);
        LocalCostRateRespVO resp = LocalCostRateConvert.INSTANCE.convert(localCostRate);
        // 获取供应商信息
        String vendorNameEn = nameTransferService.getCompanyNameEn(resp.getVendor());
        resp.setVendorNameEn(vendorNameEn);
        return CommonResult.success(resp);
    }

    @Operation(summary = "获得提单本地费用费率列表")
    @GetMapping("/list")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    public CommonResult<List<LocalCostRateRespVO>> getLocalCostRateList(@RequestParam("ids") Collection<Long> ids) {
        List<LocalCostRateDO> list = localCostRateService.getLocalCostRateList(ids);
        return CommonResult.success(LocalCostRateConvert.INSTANCE.convertList(list));
    }

    @Operation(summary = "审核")
    @PostMapping("/batch-audit")
    @PreAuthorize("@ss.hasPermission('doc:import-local-cost-rate:batch-audit')")
    public CommonResult<Void> batchApprove(@Valid @RequestBody LocalCostRateBatchAuditVO batchAuditVO) {
        localCostRateService.batchApprove(batchAuditVO.getIds(), true);
        return CommonResult.success();
    }

    @Operation(summary = "取消审核")
    @PostMapping("/cancel-audit")
    @PreAuthorize("@ss.hasPermission('doc:import-local-cost-rate:cancel-audit')")
    public CommonResult<Void> batchReject(@Valid @RequestBody LocalCostRateBatchAuditVO batchAuditVO) {
        localCostRateService.batchApprove(batchAuditVO.getIds(), false);
        return CommonResult.success();
    }

    @Operation(summary = "获得进口提单本地费用费率分页")
    @GetMapping("/page")
    @UseResponsePropertyAdvice
    @PreAuthorize("@ss.hasPermission('doc:import-local-cost-rate:query')")
    public CommonResult<PageResult<LocalCostRateRespVO>> getLocalCostRatePage(@Valid LocalCostRatePageReqVO pageVO) {
        PageResult<LocalCostRateDO> pageResult = localCostRateService.getLocalCostRatePage(pageVO);
        List<LocalCostRateRespVO> results = LocalCostRateConvert.INSTANCE.convertList(pageResult.getList());
        // 获取供应商信息
        Set<String> codes = results.stream().map(LocalCostRateRespVO::getVendor).filter(Objects::nonNull)
            .filter(name -> !name.isEmpty()).collect(Collectors.toSet());
        Map<String, String> companyNameMap = nameTransferService.getCompanyNameMap(new ArrayList<>(codes));
        results.forEach(resp -> resp.setVendorNameEn(companyNameMap.getOrDefault(resp.getVendor(), null)));
        return CommonResult.success(new PageResult<>(results,pageResult.getTotal()));
    }

    @Operation(summary = "excel导出")
    @GetMapping("/excel-export")
    @Parameter(name = "portCode", description = "港口代码")
    @Parameter(name = "exImType", description = "进出口类型 EXPORT=出口 IMPORT=进口")
    @PreAuthorize("@ss.hasPermission('doc:import-local-cost-rate:export')")
    public void exportExcelTemplate(HttpServletResponse response, @RequestParam(value = "portCode", required = false) String portCode
            , @RequestParam(value = "exImType",required = false) String exImType) throws IOException {
        List<LocalCostRateExportVO> exportList = localCostRateService.getExportList(portCode, exImType);
        // FIXME 一定要向response写数据之前设置响应头，否则会出现文件下载失败
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("localCostRate导入模板.xlsx", StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        ExcelUtils.write(response, "localCostRateData.xls", "模版", LocalCostRateExportVO.class, exportList);
    }

    @Operation(summary = "全量的基础信息库费项信息查询")
    @GetMapping("/getAllFinanceItems")
    public CommonResult<List<FinanceItemRespVO>> getAllFinanceItems() {
        List<FinanceItemRespVO> financeItemRespVos = FinanceItemConvert.INSTANCE.convert(financeItemApi.listAll().getCheckedData());
        return CommonResult.success(financeItemRespVos);
    }
}
